package com.enzo.prms.common.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtil {
	private static String DEFAULT_DATEFORMAT="yyyy-MM-dd HH:mm";
	
	private DateUtil() {
	}

	public static Timestamp getCurrentDateTime() {
		return new Timestamp(System.currentTimeMillis());
	}

	public static Timestamp getTimestamp() {
		return new Timestamp(getDate().getTime());
	}

	public static Date getDate() {
		String default_timezone = "Asia/Shanghai";
		TimeZone tz = TimeZone.getTimeZone(default_timezone);
		Calendar calendar = Calendar.getInstance(tz);
		Integer offset = 0;
		calendar.add(Calendar.DATE, offset);
		return calendar.getTime();
	}
	
	/**
	 * 2013-05-22 18:00
	 * @param dateStr
	 * @return
	 */
	public static Date praseDate(String dateStr,String dateFormat){
		if(StringUtil.isEmpty(dateFormat)){
			dateFormat=DEFAULT_DATEFORMAT;
		}
		boolean flag=false;
		if(StringUtil.isNotEmpty(dateStr)){
			if(dateStr.length()==16){
				flag=true;
			}else if (dateStr.length()==10) {
				dateStr+=" 00:00";
				flag=true;
			}
			if(flag){
				try {
					SimpleDateFormat sf=new SimpleDateFormat(dateFormat);
					Date date=sf.parse(dateStr);
					return date;
				} catch (ParseException e) {
					e.printStackTrace();
				} 
			}
		}
		return null;
	}
	
	public static String formatDate(Date source,String dateFormat){
//		String default_timezone = "Asia/Shanghai";
//		TimeZone tz = TimeZone.getTimeZone(default_timezone);
//		TimeZone.setDefault(tz);
		if(StringUtil.isEmpty(dateFormat)){
			dateFormat=DEFAULT_DATEFORMAT;
		}
		if(source!=null){
			SimpleDateFormat sf=new SimpleDateFormat(dateFormat);
			return sf.format(source);
		}
		return null;
	}
	
	/**
	 * 获得指定日期相加减后的一天
	 * @param date
	 * @param num 可正负
	 * @return
	 */
	public static Date getAnotherDate(Date date,int num){
		Calendar calendar= Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_YEAR, num);
		return calendar.getTime();
	}
	
	/**
	 * 获得指定日期在一年中的天数
	 * @param date
	 * @return
	 */
	public static int getDay(Date date){
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.DAY_OF_YEAR);
	}
	
	/**
	 * 计算指定日期与当前日期的差
	 * @param date
	 * @return
	 */
	public static int getDayDiff(Date date1,Date date2){
		System.out.println(getDay(date1)+"-"+getDay(date2));
		return getDay(date1)-getDay(date2);
	}
	
	public static void main(String[] args)throws Exception {
		Date date=getDate();
		Date date2=getAnotherDate(date, 1);
		Date date3=getAnotherDate(date, -20);
		System.out.println(date);
		System.out.println(date2);
		System.out.println(date3);
		System.out.println(getDayDiff(date,date3));
	}
}
